<template>
  <div id="app">
    <div class="box">
      <video id="video-webrtc" controls></video>
      <canvas id="canvas"></canvas>
    </div>
  </div>
</template>

<script>
import JSWebrtc from "../assets/static/jswebrtc_min.js";
export default {
  data() {
    return {
      video: null,
      canvas: null,
      ctx: null,
      timmer: null,
      mqttUrl: "wss://www.huanchenxinnengyuan.com/mqtt",
      MQTT_OPTIONS: {
        connectTimeout: 5000,
        keepalive: 5,
        clientId: "",
        username: "admin",
        password: "H9634C07116@!#",
        path: "/mqtt",
        protocolVersion: 4,
        protocolId: "MQTT",
      },
      client: null,
      topic: "shuangshuang",
    };
  },
  mounted() {
    this.receiveVideoBySrs();
    this.init();
  },
  methods: {
    /*
      从 srs 接收流数据并显示在 video 上
    */
    receiveVideoBySrs() {
      JSWebrtc; //运行引入的库函数

      this.video = document.getElementById("video-webrtc");
      var webrtcUrl = "webrtc://39.98.153.211/live/12";
      var player = new JSWebrtc.Player(webrtcUrl, {
        video: this.video,
        autoplay: true,
        onPlay: (obj) => {
          console.log("start play");
        },
      });
    },
    /* 
      初始化基础设置
    */
    init() {
      var mqtt = require("mqtt");
      this.client = mqtt.connect(this.mqttUrl, this.MQTT_OPTIONS);
      this.setMqtt(this.client);
      // 获取当前页面大小
      console.log(`window.innerWidth : ${window.innerWidth}`);
      console.log(`window.innerHeight : ${window.innerHeight}`);

      // 处理 video 和 canvas
      this.canvas = document.getElementById("canvas");
      this.ctx = this.canvas.getContext("2d");

      this.video.addEventListener("play", () => {
        // this.videoWidth:240, this.videoHeight:320
        // console.log(`this.videoWidth:${this.video.videoWidth}, this.videoHeight:${this.video.videoHeight}`);

        if (this.video.videoWidth > this.video.videoHeight) {
          this.setHorizonVideo(this.canvas); // 横向
        } else {
          this.setVerticalVideo(this.canvas); //竖向
        }

        this.video.style.visibility = "hidden";
        this.timmer = setInterval(() => {
          this.ctx.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height);
        }, 40);
      });
      this.video.addEventListener("pause", () => {
        clearInterval(this.timmer);
        console.log("clear timmer");
      });
      this.canvas.addEventListener("click", (e) => {
        let point = {
          horizon: 0,
          vertical: 0,
        };
        point.horizon = (e.clientX / this.canvas.width).toFixed(4);
        point.vertical = (e.clientY / this.canvas.height).toFixed(4);
        this.publishMsgByMqtt(point);
      });
    },
    /*
      创建 mqtt 连接并设置基本回调函数
    */
    setMqtt(client) {
      client.on("connect", () => console.log("连接成功"));
      client.on("message", (topic, msg) => {
        console.log(topic);
        console.log("message:", JSON.parse(msg.toString()));
      });
      client.on("close", () => console.log("断开连接"));
      client.subscribe(this.topic, () => console.log("订阅了主题：", this.topic));
    },
    /*
      用 mqtt 发送消息
     */
    publishMsgByMqtt(point) {
      this.client.publish(
        this.topic,
        `{"horizon":${point.horizon},"vertical":${point.vertical}}`
      );
    },
    /* 
        横向摄像头 + 横向 video 
        宽度、高度以最小的为准
    */
    setHorizonVideo(canvas) {
      const ratio = window.innerHeight / window.innerWidth;
      if (ratio >= 0.75) {
        //特别高，以宽为准
        canvas.width = window.innerWidth;
        canvas.height = canvas.width * (3 / 4);
      } else {
        //特别宽，以高为准
        canvas.height = window.innerHeight;
        canvas.width = canvas.height * (4 / 3);
      }
    },
    /* 
        竖向摄像头 + 竖向 video
        宽度、高度以最小的为准
    */
    setVerticalVideo(canvas) {
      const ratio = window.innerWidth / window.innerHeight;
      if (ratio <= 0.75) {
        //特别高，以宽为准
        canvas.width = window.innerWidth;
        canvas.height = canvas.width * (4 / 3);
      } else {
        //特别宽，以高为准
        canvas.height = window.innerHeight;
        canvas.width = canvas.height * (3 / 4);
      }
    },
  },
};
</script>
<style scoped>
.box {
  position: relative;
}

/* 绝对布局，把canvas放在video上，大小完全一致，盖住video */
video,
canvas {
  position: absolute;
}

.buttonContainer {
  position: relative;
  padding: 10px 0;
}
</style>
